package com.sk.service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import com.sk.dao.GoodDao;
import com.sk.domain.Good;

@Repository("goodService")
public class GoodService {
	@Autowired
	private GoodDao gd;

	public List<Good> findAll() {
		System.out.println(gd);
		// TODO Auto-generated method stub
		List<Good> gs = null;
		try {
			gs = gd.findAll();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return gs;
	}
	
	public Good findByID(Integer id){
		
		Good good = null;
		try {
			good = gd.findById(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return good;
	}
	
	public boolean updateGood(int id,MultipartFile file,String name,Double price,HttpServletRequest request){
		try {
			Good good = gd.findById(id);
			Good g = getGood(good,name, price, file,request);
			if(g != null){
				g.setName(name);
				g.setPrice(price);
				
				gd.update(g);
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
    public boolean delByID(int id){
		
		try {
			gd.deleteById(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		
		return true;
	}

	public void addGood(String name, double price, MultipartFile file,HttpServletRequest request) {
		// TODO Auto-generated method stub
		Good good = new Good();
		Good g = getGood(good,name, price, file,request);
		try {
			gd.add(g);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	private Good getGood(Good g,String name, double price, MultipartFile file,HttpServletRequest request){
		
		g.setName(name);
		g.setPrice(price);
		String url = request.getServletContext().getRealPath("/img");

		String fileName = UUID.randomUUID().toString().replaceAll("-", "");
		
		fileName += file.getOriginalFilename().substring(file.getOriginalFilename().toString().lastIndexOf("."),file.getOriginalFilename().length());
		
		String fileUrl = "http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/img/"+fileName;
		System.out.println(url + "/" + fileName);
		try {
			file.transferTo(new File(url + "/" + fileName));
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		g.setPic(fileUrl);
		return g;
	}

}
